package org.jeecg.module.flow.meter.tcpserver.config;

import cn.hutool.core.lang.Snowflake;
import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
import org.springframework.stereotype.Component;

import java.time.Year;

@Component
public class CustomIdGenerator implements IdentifierGenerator {
    private static final CustomIdGenerator INSTANCE = new CustomIdGenerator();
    private final Snowflake snowflake;

    public CustomIdGenerator() {
        // 初始化 Snowflake 对象
        // 需要设置机器 ID 设置为年份前两位 和数据中心 ID设置为年份后两位，可以根据自己的需求设置
        //获取当前年份
        String YearNow = Year.now().toString();
        Integer firstTwoDigits = Integer.parseInt(YearNow.substring(0,2));
        Integer lastTwoDigits = Integer.parseInt(YearNow.substring(YearNow.length()-2));
        this.snowflake = new Snowflake(firstTwoDigits, lastTwoDigits);
    }

    public static CustomIdGenerator getInstance() {
        return INSTANCE;
    }

    @Override
    public Number nextId(Object entity) {
        // 返回生成的 ID
        return snowflake.nextId();
    }
}
